<?php

namespace oa\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $realname
 * @property string $mobile
 * @property string $nickname
 * @property int $sex
 * @property string $email
 * @property string $idcard
 * @property string $avatar_src
 * @property string $intro
 * @property int $join_at
 * @property int $leave_at
 * @property int $first_work_at
 * @property string $password
 * @property int $last_login_at
 * @property int $status 状态:-1=删除;1=启用;2=停用
 * @property int $updated_at
 * @property int $created_at
 */
class User extends BaseModel implements \yii\web\IdentityInterface
{

    const SCENARIO_ADD     = 'add';
    const SCENARIO_EDIT    = 'edit';
    const SCENARIO_REMOVE  = 'remove';
    const SCENARIO_DISABLE = 'disable';
    const SCENARIO_ENABLE  = 'enable';
    const SCENARIO_CHANGE_PASSWORD  = 'change_password';
    const SCENARIO_SEEK_PASSWORD  = 'seek_password';
    const SCENARIO_EDIT_PASSWORD  = 'edit_password';
    const SCENARIO_RESET_PASSWORD  = 'reset_password';

    public $new_password;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['realname', 'mobile', 'role_id'], 'required'],
            [['sex', 'role_id', 'join_at', 'leave_at', 'first_work_at', 'last_login_at', 'status', 'updated_uid', 'updated_at', 'created_at'], 'integer'],
            [['realname', 'nickname'], 'string', 'max' => 32],
            [['mobile', 'email', 'idcard', 'password'], 'string', 'max' => 64],
            ['avatar_src', 'string', 'max' => 255],
            ['intro', 'string', 'max' => 100],
            ['mobile', 'validateMobile'],

            [['new_password'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'realname' => '姓名',
            'mobile' => '手机号',
            'nickname' => '昵称',
            'role_id' => '用户组',
            'sex' => '性别',
            'email' => '邮箱',
            'idcard' => '身份证号',
            'avatar_src' => '头像',
            'remark' => '备注',
            'join_at' => '入职时间',
            'leave_at' => '离职时间',
            'first_work_at' => '首次参加工作时间',
            'password' => '登录密码',
            'last_login_at' => '最后登录时间',
            'status' => '状态',
            'updated_uid' => '最后修改人',
            'updated_at' => '最后修改时间',
            'created_at' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            $this->autosaveTimestamp(),
            $this->autosaveUid(),
            [
                'class' => \yii\behaviors\AttributeBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'password',
                ],
                'value' => function ($event) {
                    return Yii::$app->security->generatePasswordHash($event->sender->password);
                },
            ],
            [
                'class' => \yii\behaviors\AttributeBehavior::className(),
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => 'password',
                ],
                'value' => function ($event) {
                    if ($this->scenario == self::SCENARIO_RESET_PASSWORD) {
                        return Yii::$app->security->generatePasswordHash('tta@' . $event->sender->mobile);
                    }
                    return $this->password;
                },
            ],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_ADD] = ['realname', 'mobile', 'sex', 'role_id', 'idcard', 'join_at', 'remark', 'first_work_at'];
        $scenarios[self::SCENARIO_EDIT] = ['realname', 'mobile', 'sex', 'role_id', 'idcard', 'join_at', 'leave_at', 'remark', 'first_work_at'];
        $scenarios[self::SCENARIO_REMOVE] = ['status'];
        $scenarios[self::SCENARIO_DISABLE] = ['status'];
        $scenarios[self::SCENARIO_ENABLE] = ['status'];
        $scenarios[self::SCENARIO_CHANGE_PASSWORD] = ['password', 'new_password'];
        $scenarios[self::SCENARIO_EDIT_PASSWORD] = ['password'];
        $scenarios[self::SCENARIO_SEEK_PASSWORD] = ['password'];
        $scenarios[self::SCENARIO_RESET_PASSWORD] = ['password'];
        return $scenarios;
    }

    public function validateMobile($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (in_array($this->scenario, [self::SCENARIO_ADD, self::SCENARIO_EDIT])) {
                $query = static::find()->where('status<>-1 and mobile=:mobile', [':mobile' => $this->mobile]);
                if ($this->scenario == self::SCENARIO_EDIT) {
                    $query->andWhere(['<>', 'id', $this->id]);
                }
                if ($query->exists()) {
                    $this->addError($attribute, '手机号对应的员工已存在');
                }
            }
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        if (isset($changedAttributes['last_login_at'])) { // 登录，记录登录日志
            $logUserLogin = new LogUserLogin();
            $logUserLogin->uid = $this->id;
            $logUserLogin->save();
        }
    }

    public function getRole()
    {
        return $this->hasOne(Role::className(), ['id' => 'role_id']);
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return '';
    }

    public function validateAuthKey($authKey)
    {
        return true;
    }
}
